package com.ita.tba.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import com.ita.tba.dao.UserDao;
import com.ita.tba.po.User;
import com.ita.tba.util.DbUtil;
import com.ita.tba.util.DidNumUtil;

public class UserDaoImpl implements UserDao{

	@Override
	public String findEmail(String email) {
		String sql = "select email from tbauser where email=?";
		
		String findEmail = null;
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		con = DbUtil.connect();
		
		try {
			pst = con.prepareStatement(sql);
			pst.setString(1, email);
			rs = pst.executeQuery();
			while(rs.next()) {
				findEmail = rs.getString("email");
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.free(con, pst, rs);
		}
		return findEmail;
	}

	@Override
	public int insertUser(User user) {
		String sql = "insert into tbauser(userid,email,password) values (tbauser_seq.nextval,?,?)";
		
		Connection con = null;
		PreparedStatement pst = null;
		con = DbUtil.connect();
		 
		int m = 0;
		try {
			pst = con.prepareStatement(sql);
			con.setAutoCommit(false);	
			pst.setString(1, user.getEamil());
			pst.setString(2, user.getPassword());	
			m = pst.executeUpdate();
			con.commit();
		} catch (SQLException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally {
			DbUtil.free(con, pst, null);
		}
		return m;
	}

	@Override
	public String findPassword(String email) {
		String sql = "select password from tbauser where email=?";
		
		String password = null;
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		con = DbUtil.connect();
		
		try {
			pst = con.prepareStatement(sql);
			pst.setString(1, email);
			rs = pst.executeQuery();
			while(rs.next()) {
				password = rs.getString("password");
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.free(con, pst, rs);
		}
		return password;
	}

	@Override
	public int selectUid(String email) {
		String sql = "select userid from tbauser where email=?";
		
		int uid = -1;
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		con = DbUtil.connect();
		
		try {
			pst = con.prepareStatement(sql);
			pst.setString(1, email);
			rs = pst.executeQuery();
			while(rs.next()) {
				uid = rs.getInt("userid");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.free(con, pst, rs);
		}
		return uid;
	}

}
